﻿using System;
using System.Data;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using VanTaiBLL;
using VanTaiProperty;
using Roles;
namespace VanTaiTMS.Page
{
    public partial class Quanhuyen : System.Web.UI.Page
    {
        #region[Define]

        private static bool _flag;
        private readonly clsTMDistrictBusiness _clsQuanHuyen = new clsTMDistrictBusiness();
        protected string StrAlert = "";
        public string SuggestionList = "";
        private DataTable _dtAutoComplete;
        private DataTable _dtQuanHuyen;
        private DataTable _dtQuanHuyenEdit;
        private DataTable _dtSearch;

        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermisstion();
            Autocomplete();
            if (!IsPostBack)
            {
                BindGridDropTinh();
                BindGridQuanHuyen();
                //Search();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            _flag = true;
            lbThongBaoLoi.Text = "";
            txtMaQuanHuyen.Enabled = true;
            ClearTextbox();
            txtMaQuanHuyen.Text = "MT000" + MaTuDong();
            OpenDialog("#quanhuyen");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
            imgSave.Visible = true;
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            lbThongBaoLoi.Text = "";
            txtMaQuanHuyen.Enabled = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                var chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        var dataKey = ListViewAll.DataKeys[i];
                        if (dataKey != null)
                            BindGridQuanHuyenEdit(Convert.ToInt32(dataKey.Value.ToString()));
                        OpenDialog("#quanhuyen");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                var chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                if (chkHide != null)
                {
                    if (chkHide.Checked)
                    {
                        try
                        {
                            clsTMDistrictBusiness.DeleteTMDistrict(int.Parse(ListViewAll.DataKeys[i].Value.ToString()));
                        }
                        catch
                        {
                            lbThongBaoXoa.Text = "Mẫu tin này đã tồn tại !";
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert += "<div class='alert alert-warning'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Vui lòng nhập vào từ khoá để tìm kiếm !";
                StrAlert += "</div>";
            }
            else
            {
                Search();
            }
        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            drFilterTinh.SelectedIndex = -1;
            BindGridQuanHuyen();
        }
        //---------------button-popup---------------------
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {
            BindGridDropTinh();
        }
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (txtTenQuanHuyen.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào tên quận huyện !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtMaQuanHuyen.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào mã quận huyện !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drTinh.SelectedIndex == 0)
            {
                lbThongBaoLoi.Text = "Vui lòng chọn tỉnh !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtMaQuanHuyen.Text != "" && txtTenQuanHuyen.Text != "" && drTinh.SelectedIndex != 0)
            {
                Insert();
            }
        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {
            
        }
        protected void drFilterTinh_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGridQuanHuyen();
        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        //-------------list-view-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyQuanHuyen, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                txtMaQuanHuyen.Enabled = false;
                if (e.CommandName == "Accept")
                {
                    if (Edit == false)
                    {
                        imgSave.Visible = false;
                        string senderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridQuanHuyenEdit(int.Parse(senderId));
                        OpenDialog("#quanhuyen");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                    else
                    {
                        imgSave.Visible = true;
                        string senderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridQuanHuyenEdit(int.Parse(senderId));
                        OpenDialog("#quanhuyen");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var linkName = (LinkButton)e.Item.FindControl("linkTenQuanHuyen");
                string jsDouble = ClientScript.GetPostBackClientHyperlink(linkName, "");
                linkName.Attributes["ondblclick"] = jsDouble;
                linkName.Attributes["onclick"] = "return false;";
            }
        }
        //-----------pagger-----------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            DataPagerListAll.PageSize = 17;
            BindGridQuanHuyen();
        }

        //---------Check-all--------------
        protected void chkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
        }
        protected void LinkThemNhanhTinh_Click(object sender, EventArgs e)
        {
            OpenDialog("#ThemNhanhTinh");
        }

        #endregion

        #region[Function]

        protected void BindGridQuanHuyen()
        {
            if (drFilterTinh.SelectedValue != "-1")
            {
                _dtQuanHuyen = _clsQuanHuyen.BindGirdTMDistrictFilterTinh(Convert.ToInt32(drFilterTinh.SelectedValue));
            }
            else
            {
                _dtQuanHuyen = _clsQuanHuyen.BindGirdTMDistrict(txtSearch.Text);
            }
            if (_dtQuanHuyen != null && _dtQuanHuyen.Rows.Count > 0)
            {
                ListViewAll.DataSource = _dtQuanHuyen;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;

                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }

        protected void BindGridQuanHuyenEdit(int id)
        {
            _dtQuanHuyenEdit = _clsQuanHuyen.BindGirdTMDistrictDetail(id);
            if (_dtQuanHuyenEdit != null && _dtQuanHuyenEdit.Rows.Count > 0)
            {
                lbID.Text = _dtQuanHuyenEdit.Rows[0]["STT"].ToString();
                lbIDXoa.Text = _dtQuanHuyenEdit.Rows[0]["STT"].ToString();
                txtMaQuanHuyen.Text = _dtQuanHuyenEdit.Rows[0]["MaQuanHuyen"].ToString();
                txtTenQuanHuyen.Text = _dtQuanHuyenEdit.Rows[0]["TenQuanHuyen"].ToString();
                txtTenQuanHuyenE.Text = _dtQuanHuyenEdit.Rows[0]["TenQuanHuyenE"].ToString();
                txtTenQuanHuyenC.Text = _dtQuanHuyenEdit.Rows[0]["TenQuanHuyenC"].ToString();
                txtGhiChu.Text = _dtQuanHuyenEdit.Rows[0]["GhiChu"].ToString();
                if (_dtQuanHuyenEdit.Rows[0]["IDTinh"] == DBNull.Value)
                {
                    drTinh.SelectedIndex = -1;
                }
                else
                {
                    drTinh.SelectedValue = _dtQuanHuyenEdit.Rows[0]["IDTinh"].ToString();
                }
            }
        }

        protected void BindGridDropTinh()
        {
            var clsTinh = new clsTMProvinceBusiness();
            DataTable dtTinh = clsTinh.BindGirdTMProvince("");
            if (dtTinh != null && dtTinh.Rows.Count > 0)
            {
                drTinh.Items.Clear();
                drTinh.Items.Add(new ListItem("---Vui lòng chọn tỉnh---", "-1"));
                drTinh.DataSource = dtTinh;
                drTinh.DataValueField = "STT";
                drTinh.DataTextField = "TenTinh";
                drTinh.DataBind();

                drFilterTinh.Items.Clear();
                drFilterTinh.Items.Add(new ListItem("---Vui lòng chọn tỉnh---", "-1"));
                drFilterTinh.DataSource = dtTinh;
                drFilterTinh.DataValueField = "STT";
                drFilterTinh.DataTextField = "TenTinh";
                drFilterTinh.DataBind();
            }
        }

        //Insert
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            _dtQuanHuyen = _clsQuanHuyen.BindGirdTMDistrict("");
            if (_dtQuanHuyen != null && _dtQuanHuyen.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtQuanHuyen.Rows)
                {
                    if (txtMaQuanHuyen.Text == dr["MAQuanHuyen"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected bool CheckInsertnName()
        {
            bool kiemtra = false;
            _dtQuanHuyen = _clsQuanHuyen.BindGirdTMDistrict("");
            if (_dtQuanHuyen != null && _dtQuanHuyen.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtQuanHuyen.Rows)
                {
                    if (txtTenQuanHuyen.Text == dr["TENQuanHuyen"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void Insert()
        {
            //Insert
            if (_flag)
            {
                InsertQuanHuyen();
            }
            else //Update
            {
                UpdateQuanHuyen();
            }
        }
        protected void InsertQuanHuyen()
        {
            try
            {
                if (CheckInsert())
                {
                    lbThongBaoLoi.Text = "Mã quận huyện này đã tồn tại !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    if (CheckInsertnName())
                    {
                        lbThongBaoLoi.Text = "Tên quận huyện này đã tồn tại !";
                        OpenDialog("#thongbao");
                        updatePanelThongBao.Update();
                    }
                    else
                    {
                        var obj = new clsTMDistrictProperty
                        {
                            District_Alias = txtMaQuanHuyen.Text,
                            District_Name = txtTenQuanHuyen.Text,
                            District_NameC = txtTenQuanHuyenC.Text,
                            District_NameE = txtTenQuanHuyenE.Text,
                            Province_ID = int.Parse(drTinh.SelectedValue),
                            District_Note = txtGhiChu.Text
                        };
                        clsTMDistrictBusiness.InsertTMDistrict(obj);
                        lbThongBaoLoi.Text = "Thêm mới thành công mẫu tin !";
                        OpenDialog("#thongbao");
                        updatePanelThongBao.Update();
                        BindGridQuanHuyen();
                        ClearTextbox();
                        txtMaQuanHuyen.Text = "MT000" + MaTuDong();
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                updatePanelThongBao.Update();
            }
        }

        protected void UpdateQuanHuyen()
        {
            try
            {
                var obj = new clsTMDistrictProperty
                {
                    District_ID = Convert.ToInt32(lbID.Text),
                    District_Alias = txtMaQuanHuyen.Text,
                    District_Name = txtTenQuanHuyen.Text,
                    District_NameC = txtTenQuanHuyenC.Text,
                    District_NameE = txtTenQuanHuyenE.Text,
                    Province_ID = int.Parse(drTinh.SelectedValue),
                    District_Note = txtGhiChu.Text
                };
                clsTMDistrictBusiness.UpdateTMDistrict(obj);
                lbThongBaoLoi.Text = "Cập nhật thành công mẫu tin !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
                BindGridQuanHuyenEdit(int.Parse(lbID.Text));
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }

        //Search
        protected void Search()
        {
            _dtSearch = _clsQuanHuyen.BindGirdTMDistrict(txtSearch.Text);
            if (_dtSearch != null && _dtSearch.Rows.Count > 0)
            {
                ListViewAll.DataSource = _dtSearch;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + _dtSearch.Rows.Count + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }

        //Autocomplete
        protected void Autocomplete()
        {
            _dtAutoComplete = _clsQuanHuyen.BindGirdTMDistrict("");
            if (_dtAutoComplete != null && _dtAutoComplete.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtAutoComplete.Rows)
                {
                    if (string.IsNullOrEmpty(SuggestionList))
                    {
                        SuggestionList += "\"" + dr["MaQuanHuyen"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["TenQuanHuyen"].ToString().Replace("\n", " ") + "\",";
                    }
                    else
                    {
                        SuggestionList += "\"" + dr["MaQuanHuyen"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["TenQuanHuyen"].ToString().Replace("\n", " ") + "\",";
                    }
                }
            }
        }

        #endregion

        #region[MaTangTuDong]

        protected int MaTuDong()
        {
            int i = 0;
            _dtQuanHuyen = _clsQuanHuyen.BindGirdTMDistrict("");
            if (_dtQuanHuyen != null && _dtQuanHuyen.Rows.Count > 0)
            {
                int max = Convert.ToInt32(_dtQuanHuyen.Rows[0]["STT"].ToString());
                for (i = 0; i < _dtQuanHuyen.Rows.Count; i++)
                {
                    if (int.Parse(_dtQuanHuyen.Rows[i]["STT"].ToString()) > max)
                    {
                        max = Convert.ToInt32(_dtQuanHuyen.Rows[i]["STT"].ToString());
                    }
                }
                i = max + 1;
            }
            return i;
        }

        #endregion

        #region[ClearTextBox]

        protected void ClearTextbox()
        {
            txtGhiChu.Text = "";
            txtTenQuanHuyenE.Text = "";
            txtTenQuanHuyenC.Text = "";
            txtTenQuanHuyen.Text = "";
            txtMaQuanHuyen.Text = "";
            drTinh.SelectedIndex = -1;
        }

        #endregion

        #region[OpenDialog]

        private void OpenDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }

        private void CloseDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }

        #endregion

        #region[Permisstion]
        protected void CheckPermisstion()
        {
            HttpCookie cookie = Request.Cookies["UserLogin"];
            if (cookie != null)
            {
                bool Is_Page_All = SecurityServices.HasPermisstionPage(StringContent.QuanLyQuanHuyen, int.Parse(cookie["RolesID"]), true);
                if (Is_Page_All == true)
                {
                    bool AddNew = SecurityServices.HasPermisstion(StringContent.QuanLyQuanHuyen, int.Parse(cookie["RolesID"]), TypeaAudit.AddNew);
                    if (AddNew == false)
                    {
                        cmdAddNew.Visible = false;
                    }
                    else
                    {
                        cmdAddNew.Visible = true;
                    }
                    bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyQuanHuyen, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                    if (Edit == false)
                    {
                        cmdEdit.Visible = false;
                    }
                    else
                    {
                        cmdEdit.Visible = true;
                    }
                    bool Del = SecurityServices.HasPermisstion(StringContent.QuanLyQuanHuyen, int.Parse(cookie["RolesID"]), TypeaAudit.Delete);
                    if (Del == false)
                    {
                        cmdDel.Visible = false;
                    }
                    else
                    {
                        cmdDel.Visible = true;
                    }
                }
                else
                {
                    Response.Redirect("error-page.aspx");
                }
            }
        }
        #endregion
    }
}